﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.RegularExpressions;

namespace StarUtils.Http
{
    internal static class HttpClientBuilderFactory
    {
        private static readonly IDictionary<string, HttpClient> _httpClients = new ConcurrentDictionary<string, HttpClient>();

        private static readonly Regex _domainRegex = new Regex("(http|https)://(?<domain>[^(:|/]*)", RegexOptions.IgnoreCase);

        public static HttpClient CreateClient(string url, TimeSpan timeout)
        {
            string domainByUrl = GetDomainByUrl(url);
            if (_httpClients.ContainsKey(domainByUrl))
            {
                return _httpClients[domainByUrl];
            }

            HttpClient httpClient = Create(timeout);
            _httpClients[domainByUrl] = httpClient;
            return httpClient;
        }

        private static string GetDomainByUrl(string url)
        {
            return _domainRegex.Match(url).Value;
        }

        private static HttpClient Create(TimeSpan timeout)
        {
            return new HttpClient(new HttpClientHandler
            {
                UseProxy = false
            })
            {
                Timeout = timeout
            };
        }
    }
}
